import { Menu } from "../models/menu";
import { AuthItem, Role } from "../models/role";

export default function rolModule(app, opt, next) {
  app.get("list", async () => {
    const list = await Role.find();
    return list;
  });
  app.get("/menu/list", async () => {
    const list = await Menu.find({});
    return list;
  });

  app.get("/auth-list", async () => {
    const menus = await Menu.find({}).lean(true);
    const all = menus.reduce((acc, v) => {
      return [...acc, ...v.children];
    }, []);

    const items = await AuthItem.find();
    const pages = all.filter((v) => v.key && v.key !== "/" && !v.children);

    return [
      ...pages.map((v) => {
        return {
          value: v.key,
          name: v.label,
          type: "page",
        };
      }),
      ...items,
    ];
  });

  app.post("add", async (req) => {
    const model = new Role(req.body);
    await model.save();
    return model;
  });
  app.post("update", async (req) => {
    const { id, ...rest } = req.body;
    await Role.updateOne({ _id: id }, { $set: rest });
    return { msg: "ok" };
  });

  app.post("auth/add", async (req) => {
    const model = new AuthItem(req.body);
    await model.save();
    return model;
  });

  app.post("auth/update", async (req) => {
    const { id, ...rest } = req.body;
    return AuthItem.updateOne({ _id: id }, rest);
  });
  next();
}
export const autoPrefix = "/role/";
